package com.leha.api.filter;

import com.leha.utils.ConvertUtils;
import com.leha.utils.DateTool;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Base64;
import java.util.Date;
import java.util.ResourceBundle;


public class ApiFilter implements Filter {

    protected FilterConfig filterConfig = null;
    private static Logger logger = LogManager.getLogger(ApiFilter.class);
    private static final String sk = ResourceBundle.getBundle("config").getString("wegame.sk");
    private static final boolean tokenCheck = Boolean.valueOf(ResourceBundle.getBundle("config").getString("wegame.tokencheck"));
    @Override
    public void destroy() {
    }

    private boolean checkAuthToken(String authToken) {
        if(authToken==null || authToken.isEmpty()) return false;
        String tokenDecode = String.valueOf(Base64.getDecoder().decode(authToken));
        if(sk.length()>= tokenDecode.length()) return false;
        if(!sk.equals(tokenDecode.substring(0, sk.length()))){
            return false;
        }
        String check = DateTool.getNowTime("yyyy-MM-dd").substring(8,10);
        if(!tokenDecode.endsWith(check)) {
            return false;
        }
        return true;
    }
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

        HttpServletRequest hsrequest = (HttpServletRequest) request;
        HttpSession session = hsrequest.getSession();

        boolean flg = false;
        String noFilterUrlParams = this.filterConfig.getInitParameter("noFilterUrlParams");
        String[] noFilterUrls = noFilterUrlParams.split(";");
        for (String url : noFilterUrls) {
            String tmpUrl = hsrequest.getContextPath() + url;
            if (tmpUrl.equalsIgnoreCase(hsrequest.getRequestURI()) || hsrequest.getRequestURI().indexOf(tmpUrl) != -1 || hsrequest.getRequestURI().indexOf(url) != -1) {
                flg = true;
                break;
            }
        }

        if (!tokenCheck || flg || checkAuthToken(hsrequest.getHeader("authToken"))) {
            chain.doFilter(request, response);
        } else {
            response.setContentType("text/html;charset=utf-8");
            PrintWriter out = response.getWriter();
            out.print("WeChatOnly!");
            out.close();
            return;
        }
    }

    public void init(FilterConfig filterConfig) throws ServletException {
        this.filterConfig = filterConfig;
    }

}
